<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const formModel = ref({
  username: '',
  nickname: '',
  email: ''
});
const isEditing = ref(false);

// 初始化表单数据
onMounted(() => {
  formModel.value = {
    username: userStore.user.username,
    nickname: userStore.user.nickname,
    email: userStore.user.email || ''
  };
});

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value;
};

// 保存资料
const saveProfile = () => {
  userStore.setUser({
    ...userStore.user,
    ...formModel.value
  });
  isEditing.value = false;
  ElMessage.success('资料保存成功');
};
</script>

<template>
  <div class="profile-container">
    <el-card>
      <div class="card-header">
        <h2>基本资料</h2>
        <el-button 
          type="primary" 
          size="small" 
          @click="isEditing ? saveProfile() : toggleEdit()"
        >
          {{ isEditing ? '保存' : '编辑' }}
        </el-button>
      </div>
      
      <el-form label-width="120px" class="profile-form">
        <el-form-item label="用户名">
          <el-input 
            v-model="formModel.username" 
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input 
            v-model="formModel.nickname" 
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input 
            v-model="formModel.email" 
            :disabled="!isEditing"
            type="email"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.profile-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .profile-form {
    margin-top: 20px;
  }
}
</style>